package lib.bone.audit.workload.listener;

import cn.hutool.core.io.FileUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.metadata.CellExtra;
import lib.bone.access.config.cycle.NepuCycleService;
import lib.bone.access.constant.WorkloadSourceConst;
import lib.bone.access.constant.WorkloadTypeConst;
import lib.bone.audit.workload.attach.ResearchAttach;
import lib.bone.audit.workload.domain.NepuWorkload;
import lib.bone.audit.workload.domain.dto.SupplementImportDTO;
import lib.bone.audit.workload.domain.dto.TeachingWorkloadImportDTO;
import lib.bone.audit.workload.service.NepuWorkloadService;
import lib.bone.common.utils.JsonUtil;
import lib.bone.system.domain.entity.SysUser;
import lib.bone.system.module.iojob.constant.JobStatusConst;
import lib.bone.system.module.iojob.domain.IOJob;
import lib.bone.system.module.iojob.domain.IOLog;
import lib.bone.system.module.iojob.service.IOJobService;
import lib.bone.system.service.SysDeptService;
import lib.bone.system.service.SysUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.Example;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

@Slf4j
public class AddWorkloadListener extends AnalysisEventListener<SupplementImportDTO>{


    /**
     * 文件父路径
     */
    String fileParentPath;
    /**
     * 周期ID
     */
    String cycleId;
    /**
     * 父周期ID
     */
    String parentCycleId;
    /**
     * 周期名称
     */
    String cycleName;
    /**
     * 任务ID
     */
    String ioJobId;
    /**
     * 用户服务
     */
    SysUserService userService;
    /**
     * 工作量服务
     */
    NepuWorkloadService workloadService;

    /**
     * 导入导出服务
     */
    IOJobService ioJobService;
    /**
     * 操作日志
     */
    List<IOLog> logs = new ArrayList<>();



    public AddWorkloadListener(SysUserService userService, NepuWorkloadService workloadService, IOJobService ioJobService, String cycleName, String cycleId, String ioJobId, String fileParentPath){
        this.userService = userService;
        this.workloadService = workloadService;
        this.ioJobService = ioJobService;
        this.cycleId = cycleId;
        this.ioJobId = ioJobId;
        this.fileParentPath = fileParentPath;
        this.cycleName = cycleName;
    }

    public AddWorkloadListener(SysUserService userService, NepuWorkloadService workloadService, IOJobService ioJobService, String cycleName, String cycleId, String parentCycleId,String ioJobId, String fileParentPath){
        this.userService = userService;
        this.workloadService = workloadService;
        this.ioJobService = ioJobService;
        this.cycleId = cycleId;
        this.parentCycleId=parentCycleId;
        this.ioJobId = ioJobId;
        this.fileParentPath = fileParentPath;
        this.cycleName = cycleName;
    }


    @Override
    public void invoke(SupplementImportDTO supplementImportDTO, AnalysisContext analysisContext) {
        System.out.println("进入事务！");
        Optional<SysUser> userOp = userService.findByUserName(supplementImportDTO.getUserName());
        if (!userOp.isPresent()) {
            log.info("{}对应用户信息不存在", supplementImportDTO.getUserName());
            return;
        }
        SysUser user = userOp.get();
        Long userId = user.getId();
        // 查询工作量记录是否存在
        NepuWorkload workload = new NepuWorkload();
        workload.setCycleId(cycleId);
        workload.setParentId(parentCycleId);
        workload.setUserId(userId);
        ResearchAttach researchAttach = new ResearchAttach();
        if (supplementImportDTO.getWorkloadType().equals(WorkloadTypeConst.RESEARCH_ADD)){
            workload.setWorkloadType(WorkloadTypeConst.RESEARCH);
            researchAttach.setResearchName(WorkloadTypeConst.RESEARCH_ADD);
        }else if (supplementImportDTO.getWorkloadType().equals(WorkloadTypeConst.TEACH_ADD)){
            workload.setWorkloadType(WorkloadTypeConst.TEACH);
            researchAttach.setResearchName(WorkloadTypeConst.TEACH_ADD);
        }else {
            log.info("错误的工作量类型!");
            return;
        }
        String attach = JsonUtil.obj2String(researchAttach);
        workload.setWorkloadAttach(attach);
        workload.setRemark("["+cycleName+"]"+supplementImportDTO.getWorkloadType());
        if (supplementImportDTO.getWorkloadType().equals(WorkloadTypeConst.RESEARCH_ADD)){
            log.info("工作量类型为：科研");
            workload.setWorkloadLevel(supplementImportDTO.getWorkloadLevel());
        }
        Example<NepuWorkload> example = Example.of(workload);
        List<NepuWorkload> queryList = workloadService.getExampleWorkloads(example);
        if (queryList.size() >= 1){
            IOLog ioLog = new IOLog();
            ioLog.setId((long) (logs.size()+1));
            ioLog.setErrMsg("已存在追加工作量记录");
            ioLog.setParams(JsonUtil.obj2String(supplementImportDTO));
            logs.add(ioLog);
            log.info("{},{}该周期已有"+supplementImportDTO.getWorkloadType(),supplementImportDTO.getUserName(),supplementImportDTO.getNickName());
        }else {
            workload.setWorkload(supplementImportDTO.getWorkload());
            workload.setUsedWorkload(0.0);
            workload.setUsedUp(0);
            workload.setWorkloadLock(1);
            workload.setWorkloadSource(WorkloadSourceConst.ADD);
            workloadService.saveOne(workload);
            log.info("{},{}写入成功追加工作量{}",supplementImportDTO.getUserName(),supplementImportDTO.getNickName(),supplementImportDTO.getWorkload());
        }

    }


    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        Optional<IOJob> ioJobOp = ioJobService.getById(ioJobId);
        if (!ioJobOp.isPresent()) {
            log.error("导入任务丢失");
            return;
        }
        IOJob ioJob = ioJobOp.get();
        String filePath = fileParentPath+ File.separator+ioJob.getId()+File.separator+"log.xlsx";
        FileUtil.touch(filePath);
        EasyExcel.write(filePath,IOLog.class).sheet("sheet").doWrite(logs);

        ioJob.setJobStatus(JobStatusConst.FINISHED);
        ioJob.setLogFilePath(filePath);
        ioJobService.updateOne(ioJob);
        log.info("追加工作量导入完成");
    }

}
